package br.com.social.mobile.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;

import br.com.social.mobile.dao.GpsDeviceDAO;
import br.com.social.mobile.dao.PositionDAO;
import br.com.social.mobile.entities.GpsDevice;
import br.com.social.mobile.entities.Position;
import br.com.social.mobile.exception.TrackerServiceException;
import br.com.social.mobile.rest.util.dto.RankingDto;


public class RankingHandler {
	
	private Logger logger = Logger.getLogger(RankingHandler.class);


	public List<RankingDto> getListRanking() throws TrackerServiceException {
		logger.info("Start getListGpsPosition");
		PositionDAO positionDAO = new PositionDAO();
		List<Position> lstPositions = positionDAO.maxSpeedGroupByUser();
		
		HashMap<Long, GpsDevice> mapUsers = mapUsers();
		
		RankingDto rankingDto;
		List<RankingDto> lstRankingDto = new ArrayList<RankingDto>();
		GpsDevice gpsDevice = null;
		
		for (Position position : lstPositions) {
			if (mapUsers != null) {
				gpsDevice = mapUsers.get(position.getNuImei());
			}
			
			rankingDto = new RankingDto();
			rankingDto.setDate(position.getDtPosition().getTime());
			rankingDto.setLatitude(String.valueOf(position.getNuLatitude()));
			rankingDto.setLongitude(String.valueOf(position.getNuLongitude()));
			if (gpsDevice != null) {
				rankingDto.setModel(gpsDevice.getDsDescription());
				rankingDto.setName(gpsDevice.getDsName());
			}
			
			rankingDto.setSpeed(String.valueOf(position.getNuSpeed()));
			
			logger.info("position: " + position);
			logger.info("rankingDto: " + rankingDto);
			logger.info("rankingDto.getName(): " + rankingDto.getName());
			logger.info("rankingDto.getSpeed(): " + rankingDto.getSpeed());
			lstRankingDto.add(rankingDto);
			
		}
		logger.info("Criou a lista de ranking");
		return lstRankingDto;
		
	}	



	private HashMap<Long, GpsDevice> mapUsers() {
		GpsDeviceDAO gpsDeviceDAO = new GpsDeviceDAO();
		List<GpsDevice> lstUsers = gpsDeviceDAO.findAll();
		HashMap<Long, GpsDevice> hashMap = new HashMap<Long, GpsDevice>();
		
		for (GpsDevice gpsDevice : lstUsers) {
			hashMap.put(gpsDevice.getNuImei(), gpsDevice);
		}
		
		return hashMap;
	}

	
}
